#include<iostream>
#include<unistd.h>
#include<cstring>
#include<cerrno>
#include<sys/types.h>
#include<sys/wait.h>

int main()
{
    //创建pipe
    int pipefd[2]={0};
    int n=pipe(pipefd);
    if(n<0)
    {
        std::cerr<<"errno:"<<errno<<strerror(errno)<<std::endl;
        exit(1);
    }

    pid_t id=fork();
    if(id==0)
    {
        close(pipefd[1]);//子进程关闭写

        //通信
        char buffer[1024];
        while(true)
        {
            int n=read(pipefd[0],buffer,sizeof(buffer)-1);
            if(n>0)
            {
                buffer[n]='\0';
                std::cout<<"i am child receive from father:   "<<buffer<<std::endl;
            }

        }
        close(pipefd[0]);
        exit(0);
    }



    close(pipefd[0]);
    char buffer[1024];
    std::string str="i am father";
    while (true)
    {
       snprintf(buffer,sizeof(buffer),"%s\n",str.c_str());
        write(pipefd[1],buffer,strlen(buffer));
        sleep(1);

    }
    close(pipefd[1]);
    int status=0;
    waitpid(id,&status,0);
    return 0;
    
    





}